import 'package:flutter/material.dart';
import '../services/file_service.dart';
import '../models/file_item.dart';
import '../widgets/file_list_view.dart';
import '../services/theme_service.dart';

class RecycleBinPage extends StatefulWidget {
  const RecycleBinPage({super.key});

  @override
  State<RecycleBinPage> createState() => _RecycleBinPageState();
}

class _RecycleBinPageState extends State<RecycleBinPage> {
  bool _isLoading = false;
  List<Map<String, dynamic>> _deletedFiles = [];
  Set<int> _selectedFileIds = {};
  String? _errorMessage;
  bool _isRestoring = false;
  bool _isDeleting = false;

  @override
  void initState() {
    super.initState();
    _loadDeletedFiles();
  }

  Future<void> _loadDeletedFiles() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final files = await FileService.getDeletedFiles();
      setState(() {
        _deletedFiles =
            files
                .map(
                  (file) => {
                    'id': file.id,
                    'file_name': file.filename,
                    'file_type': file.fileType,
                    'file_size': file.size,
                    'upload_time': file.uploadTime,
                  },
                )
                .toList();
      });
    } catch (e) {
      setState(() {
        _errorMessage = '获取已删除文件失败了，稍后再试试吧~';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _permanentlyDeleteFiles() async {
    if (_selectedFileIds.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请先选择要删除的文件哦~'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 分离文件ID和目录ID
    final List<int> fileIds = [];
    final List<int> directoryIds = [];

    for (final id in _selectedFileIds) {
      if (id < 0) {
        // 负数ID是目录，转为正数
        directoryIds.add(-id);
      } else {
        // 正数ID是文件
        fileIds.add(id);
      }
    }

    // 计算选中的文件数和目录数
    final int selectedFilesCount = fileIds.length;
    final int selectedDirectoriesCount = directoryIds.length;
    String confirmMessage = '确定要永久删除';
    if (selectedDirectoriesCount > 0) {
      confirmMessage += ' $selectedDirectoriesCount 个文件夹';
      if (selectedFilesCount > 0) {
        confirmMessage += '和';
      }
    }
    if (selectedFilesCount > 0) {
      confirmMessage += ' $selectedFilesCount 个文件';
    }
    confirmMessage += '吗？\n删除后将无法恢复！';

    if (selectedDirectoriesCount > 0) {
      confirmMessage += '\n\n注意：删除文件夹将同时删除其中的所有子文件和子文件夹。';
    }

    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('永久删除确认'),
            content: Text(confirmMessage),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                style: TextButton.styleFrom(foregroundColor: Colors.red),
                child: const Text('删除'),
              ),
            ],
          ),
    );

    if (confirmed != true) return;

    setState(() {
      _isDeleting = true;
      _errorMessage = null;
    });

    try {
      final result = await FileService.permanentlyDeleteItems(
        directoryIds: directoryIds.isNotEmpty ? directoryIds : null,
        fileIds: fileIds.isNotEmpty ? fileIds : null,
      );

      if (!result.isSuccess || result.data == null) {
        throw Exception(result.message);
      }

      // 重新加载文件列表
      await _loadDeletedFiles();

      if (!mounted) return;

      // 解析结果并显示提示
      final directoriesSuccess =
          result.data!.data?['directories']?['success_count'] ?? 0;
      final directoriesAffectedFiles =
          result.data!.data?['directories']?['affected_files_count'] ?? 0;
      final filesSuccess = result.data!.data?['files']?['success_count'] ?? 0;
      final totalSuccess = result.data!.data?['total_success_count'] ?? 0;
      final totalFailed = result.data!.data?['total_failed_count'] ?? 0;

      if (totalFailed > 0) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('成功删除$totalSuccess个项目，$totalFailed个项目删除失败'),
            backgroundColor: Colors.orange,
          ),
        );
      } else {
        String successMessage = '成功删除';
        if (directoriesSuccess > 0) {
          successMessage += '$directoriesSuccess个文件夹';
          if (directoriesAffectedFiles > 0) {
            successMessage += '（包含$directoriesAffectedFiles个子文件）';
          }
          if (filesSuccess > 0) {
            successMessage += '和';
          }
        }
        if (filesSuccess > 0) {
          successMessage += '$filesSuccess个文件';
        }
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(successMessage),
            backgroundColor: Colors.green,
          ),
        );
      }

      // 清空选中状态
      setState(() {
        _selectedFileIds.clear();
      });
    } catch (e) {
      setState(() {
        _errorMessage = '永久删除失败了，稍后再试试吧~';
      });
    } finally {
      setState(() {
        _isDeleting = false;
      });
    }
  }

  Future<void> _batchRestoreFiles() async {
    if (_selectedFileIds.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请先选择要恢复的文件哦~'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('恢复确认'),
            content: Text('确定要恢复选中的 ${_selectedFileIds.length} 个文件吗？'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                style: TextButton.styleFrom(
                  foregroundColor: Theme.of(context).primaryColor,
                ),
                child: const Text('恢复'),
              ),
            ],
          ),
    );

    if (confirmed != true) return;

    try {
      setState(() {
        _isRestoring = true;
      });

      final result = await FileService.batchRestoreFiles(
        _selectedFileIds.toList(),
      );

      // 刷新列表
      await _loadDeletedFiles();

      if (!result.isSuccess || result.data == null) {
        throw Exception(result.message);
      }

      final successCount = result.data!.successCount;
      final failedCount = result.data!.failedCount;

      if (mounted) {
        if (failedCount > 0) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('成功恢复$successCount个文件，$failedCount个文件恢复失败'),
              backgroundColor: Colors.orange,
            ),
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('成功恢复$successCount个文件'),
              backgroundColor: Colors.green,
            ),
          );
        }
      }

      // 清空选择
      setState(() {
        _selectedFileIds.clear();
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('恢复文件失败：$e'), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isRestoring = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          _selectedFileIds.isNotEmpty
              ? '已选择 ${_selectedFileIds.length} 个文件'
              : '回收站 (${_deletedFiles.length}个)',
          style: theme.appBarTheme.titleTextStyle,
          textAlign: TextAlign.center,
        ),
        backgroundColor: Theme.of(context).primaryColor,
        actions: [
          if (_selectedFileIds.isNotEmpty) ...[
            IconButton(
              icon: const Icon(Icons.restore),
              onPressed: _isRestoring ? null : _batchRestoreFiles,
              tooltip: '恢复选中文件',
            ),
            IconButton(
              icon: const Icon(Icons.delete_forever),
              onPressed: _isDeleting ? null : _permanentlyDeleteFiles,
              tooltip: '永久删除选中文件',
            ),
          ],
          if (_deletedFiles.isNotEmpty)
            IconButton(
              icon: Icon(
                _selectedFileIds.length == _deletedFiles.length
                    ? Icons.deselect
                    : Icons.select_all,
              ),
              tooltip:
                  _selectedFileIds.length == _deletedFiles.length
                      ? '取消全选'
                      : '全选',
              onPressed: () {
                setState(() {
                  if (_selectedFileIds.length == _deletedFiles.length) {
                    _selectedFileIds.clear();
                  } else {
                    _selectedFileIds =
                        _deletedFiles.map((f) => f['id'] as int).toSet();
                  }
                });
              },
            ),
        ],
      ),
      body:
          _errorMessage != null
              ? Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      _errorMessage!,
                      style: const TextStyle(color: Colors.red),
                    ),
                    const SizedBox(height: 16),
                    ElevatedButton(
                      onPressed: _loadDeletedFiles,
                      child: const Text('重试'),
                    ),
                  ],
                ),
              )
              : FileListView(
                files: _deletedFiles,
                isLoading: _isLoading,
                isSelectMode: _selectedFileIds.isNotEmpty,
                selectedFileIds: _selectedFileIds,
                onFileSelected: (fileId) {
                  setState(() {
                    if (_selectedFileIds.contains(fileId)) {
                      _selectedFileIds.remove(fileId);
                    } else {
                      _selectedFileIds.add(fileId);
                    }
                  });
                },
                onFileTap: (fileId, fileName, fileType) {
                  // 回收站中的文件不支持预览
                },
                emptyWidget: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ShaderMask(
                        shaderCallback: (Rect bounds) {
                          return LinearGradient(
                            colors: [
                              Theme.of(context).primaryColor,
                              Colors.pinkAccent,
                            ],
                          ).createShader(bounds);
                        },
                        child: const Icon(Icons.delete_outline, size: 64),
                      ),
                      const SizedBox(height: 16),
                      const Text(
                        '回收站是空的呢~',
                        style: TextStyle(fontSize: 16, color: Colors.grey),
                      ),
                    ],
                  ),
                ),
                onRefresh: _loadDeletedFiles,
              ),
    );
  }
}
